package com.atguigu.edu.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.func.DimSinkFunction;
import com.atguigu.edu.realtime.app.func.TableProcessFunction;
import com.atguigu.edu.realtime.beans.TableProcess;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

/**
 * @ClassName DimApp
 * @Description TODO
 * @Author$ 邢家俊
 * @Date 2023-5-4 22:28
 * @Version 1.0
 **/
public class DimApp {
    public static void main(String[] args) throws Exception {
        //设置执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度
        env.setParallelism(4);
        //TODO 配置检查点
      // env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
      // env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
      // env.setStateBackend(new HashMapStateBackend());
      // env.getCheckpointConfig().setCheckpointTimeout(6000L);
      // env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop101:8020/edu/ck");
      // env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
      // env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //从kafka中读取数据
        String topic ="topic_db";
        String groupId="dim_app_group";
        FlinkKafkaConsumer<String> functionDS = MyKafkaUtil.getKafkaConsumer(topic,groupId);
        DataStreamSource<String> streamSourceDS = env.addSource(functionDS);
      //streamSourceDS.print();
      //1> {"database":"edu","table":"order_detail",
        //"type":"insert","ts":1683255920,"xid":736565,"commit":true,
        //"data":{"id":29013,"course_id":435,"course_name":"2021最新Redis 6教程分布式锁，秒杀实战",
        //"order_id":27315,"user_id":41,"origin_amount":200.00,
        //"coupon_reduce":0.00,"final_amount":200.00,"create_time":"2023-05-05 11:05:21","update_time":null}}

        // 4.对流中的数据进行简单的ETL  jsonStr ---->jsonObj
        SingleOutputStreamOperator<JSONObject> flatMapDS = streamSourceDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String jsonStr, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObj = JSON.parseObject(jsonStr);
                String type = jsonObj.getString("type");
                if(!"bootstrap-start".equals(type) && !"bootstrap-complete".equals(type)){
                    out.collect(jsonObj);
                }
            }
        });
        //flatMapDS.print("flatMapDS");
        //1> {"database":"edu","table":"order_info","type":"update","ts":1683256332,"xid":776598,"commit":true,
        //"data":{"id":27859,"user_id":27,"origin_amount":200.00,"coupon_reduce":0.00,"final_amount":200.00,"order_status":"1002",
        //"out_trade_no":"122627432898194","trade_body":"尚硅谷AJAX技术等1件商品","session_id":"924cd2c7-4e27-43fb-a576-0145cac91dd1","province_id":12,
        //"create_time":"2023-05-05 11:12:12","expire_time":"2023-05-05 11:27:12","update_time":"2023-05-05 11:12:12"},"old":{"order_status":"1001","update_time":null}}
        //1> {"database":"edu","table":"order_info","type":"insert","ts":1683256332,"xid":777079,"commit":true,
        //"data":{"id":27888,"user_id":35,"origin_amount":200.00,"coupon_reduce":0.00,"final_amount":200.00,"order_status":"1001",
        //"out_trade_no":"646272518456399","trade_body":"CSS3特效实战等1件商品","session_id":"8e9b4b71-3701-43d3-85bd-b4cb9039600e","province_id":18,
        //"create_time":"2023-05-05 11:12:12","expire_time":"2023-05-05 11:27:12","update_time":null}}

        //使用FlinkCDC,读取配置流
        MySqlSource<String> mySqlSourceDS = MySqlSource.<String>builder()
                .hostname("hadoop101")
                .port(3306)
                .databaseList("edu_config") // set captured database
                .tableList("edu_config.table_process") // set captured table
                .username("root")
                .password("000000")
                .startupOptions(StartupOptions.initial())
                .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to String
                .build();
        DataStreamSource<String> mySQLDS = env.fromSource(mySqlSourceDS, WatermarkStrategy.noWatermarks(), "MySQL_Source");
//mySQLDS.print();
//4> {"before":null,
// "after":{"source_table":"test_point_question","source_type":"ALL","sink_table":"dim_test_point_question",
// "sink_type":"dim","sink_columns":"id,point_id,question_id,create_time,publisher_id,deleted","sink_pk":"id",
// "sink_extend":null},"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1683256848293,
// "snapshot":"false","db":"edu_config","sequence":null,"table":"table_process","server_id":0,
// "gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1683256848293,"transaction":null}

        //将配置流进行广播
        MapStateDescriptor<String, TableProcess> stringTableProcessMapStateDescriptor = new MapStateDescriptor<String, TableProcess>("Mysql_ds",String.class,TableProcess.class);
        BroadcastStream<String> broadcastDS = mySQLDS.broadcast(stringTableProcessMapStateDescriptor);

        BroadcastConnectedStream<JSONObject, String> connectDS = flatMapDS.connect(broadcastDS);


        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(new TableProcessFunction(stringTableProcessMapStateDescriptor));


        //将维度数据写到Phoenix表中
        dimDS.print(">>>");
        dimDS.addSink(new DimSinkFunction());

        env.execute();
    }
}
